﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SecurityExtensions.cs" company="ecblog.codeplex.com">
//   emrecoskun.net - ibrahimatay.com
// </copyright>
// <summary>
//   Defines the SecurityExtensions type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace EcBlog.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;

    public static class SecurityExtensions
    {
        private static readonly byte[] Salt = Encoding.ASCII.GetBytes("kflf6zx543");
        
        private static readonly HashSet<char> Base64Characters = new HashSet<char> 
        { 
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
            'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 
            '='
        };

        public static bool IsBase64String(this string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }

            return value[value.Length - 1] == '=' && !value.ToCharArray().Except(Base64Characters).Any();
        }

        public static string Encrypt(this string text, string secret)
        {
            var entropy = Encoding.Unicode.GetBytes(secret + Salt);

            return Convert.ToBase64String(
                ProtectedData.Protect(
                    Encoding.Unicode.GetBytes(text), entropy, DataProtectionScope.LocalMachine));
        }

        public static string Decrypt(this string text, string secret)
        {
            var entropy = Encoding.Unicode.GetBytes(secret + Salt);

            return Encoding.Unicode.GetString(
                ProtectedData.Unprotect(Convert.FromBase64String(text), entropy, DataProtectionScope.LocalMachine));
        } 
    }
}